package com.hb.umsp.util.ad;

import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class Adlogin {

    Logger logger = LoggerFactory.getLogger(Adlogin.class);

    public Map<String,String> Adlogin(String userName,String password) {
        Map<String,String> userMap = new HashMap<>();
        String host = "10.1.23.17";//AD域IP，必须填写正确 *号改为自己的IP
        String domain = "@hb-life.local";//域名后缀，例.@noker.cn.com 对应userName@
        String port = "389"; //端口，一般默认389
        String url = new String("ldap://" + host + ":" + port);//固定写法
        String user = userName.indexOf(domain) > 0 ? userName : userName
                + domain;//网上有别的方法，但是在我这儿都不好使，建议这么使用
        Hashtable env = new Hashtable();//实例化一个Env
        DirContext ctx = null;
        env.put(Context.SECURITY_AUTHENTICATION, "simple");//LDAP访问安全级别(none,simple,strong),一种模式，这么写就行
        env.put(Context.SECURITY_PRINCIPAL, user); //用户名
        env.put(Context.SECURITY_CREDENTIALS, password);//密码
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");// LDAP工厂类
        env.put(Context.PROVIDER_URL, url);//Url
        try {
            ctx = new InitialDirContext(env);// 初始化上下文
            logger.info("身份验证成功!");
            userMap = SearchADInfo(ctx, userName);
        } catch (AuthenticationException e) {
            logger.info("身份验证失败!");
            e.printStackTrace();
        } catch (javax.naming.CommunicationException e) {
            logger.info("AD域连接失败!");
            e.printStackTrace();
        } catch (Exception e) {
            logger.info("身份验证未知异常!");
            e.printStackTrace();
        } finally{
            if(null!=ctx){
                try {
                    ctx.close();
                    ctx=null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return userMap;
    }


    public Map<String,String> SearchADInfo(DirContext ctx,String username) {
        Map<String,String> usermap = new HashMap<>();
        try {
            // Create the search controls
            SearchControls searchCtls = new SearchControls();

            // Specify the search scope
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            // specify the LDAP search filter
            String searchFilter = "objectClass=User";

            // Specify the Base for the search 搜索域节点
            String searchBase = "DC=hb-life,DC=local";

            int totalResults = 0;

            String returnedAtts[] = {"Description", "displayname", "userPrincipalName","sAMAccountName"}; // 定制返回属性

            searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集

            // Search for objects using the filter
            NamingEnumeration answer = ctx.search(searchBase, searchFilter,
                    searchCtls);

            if (answer == null || answer.equals(null)) {
                logger.info("answer is null");
            } else {
                logger.info("answer not null");
            }


            boolean userState = false;
            while (answer.hasMoreElements()) {
                SearchResult sr = (SearchResult) answer.next();

                logger.info("getname=" + sr.getName());

                if (userState) {
                    break;
                }
                usermap = new HashMap<>();
                Attributes Attrs = sr.getAttributes();
                if (Attrs != null) {
                    try {
                        for (NamingEnumeration ne = Attrs.getAll(); ne
                                .hasMore(); ) {
                            Attribute Attr = (Attribute) ne.next();

                            logger.info(" AttributeID=" + Attr.getID().toString());

                            // 读取属性值
                            for (NamingEnumeration e = Attr.getAll(); e
                                    .hasMore(); totalResults++) {
                                String AttributeValues = e.next().toString();
                                logger.info(" AttributeValues="
                                        + AttributeValues);
                                //把用户信息放到map中
                                usermap.put(Attr.getID().toString(),AttributeValues);
                                if (username.equals(AttributeValues)) {
                                    userState = true;
                                    logger.info("heping" + sr.getName());
                                }
                            }
                            /* 读取属性值
                            Enumeration values = Attr.getAll();
                            if (values != null) { // 迭代
                                while (values.hasMoreElements()) {
                                    logger.info(" AttributeValues="
                                            + values.nextElement());
                                }
                            }*/
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return usermap;
    }



    public static void main(String args[]) {
        Adlogin adlogin = new Adlogin();
        Map map = adlogin.Adlogin("heping","1qaz@WSX");
    }
}
